import React, { Component } from 'react';
import { connect } from 'react-redux';
import style from '../Dictionary/Dictionary.scss';
import appStyle from '../../style.scss';
import { login, logout } from '../../actions/userAction';
import Login from '../Login';

export default function authentication(WrapedComponent) {
  class Auth extends Component {
    constructor(props) {
      super(props);

      this.state = {
        username: undefined,
        password: undefined,
        loginModalVisible: false,
      }

      this.checkLoginResolve = undefined;
    }

    getUserData() {
      return this.props.userData;
    }

    handleSubmit(username, password) {
      this.props.login(username, password).then((res) => {
        this.setState({
          loginModalVisible: false,
        })
        if (this.checkLoginResolve) {
          this.checkLoginResolve(res);
          this.checkLoginResolve = undefined;
        }
      })
    }

    checkLogin() {
      console.log('this.props.userData.isLogin', this.props.userData.isLogin)
      if (this.props.userData.isLogin) {
        return Promise.resolve(this.props.userData);
      }
      this.setState({
        loginModalVisible: true,
      });
      return new Promise((resolve => {
        this.checkLoginResolve = resolve;
      }))
    }

    render() {
      console.log('this.state.loginModalVisiblethis.state.loginModalVisible', this.props.userData);
      return (
        <div>
          <WrapedComponent
            {...this.props}
            getUserData={this.getUserData.bind(this)}
            checkLogin={this.checkLogin.bind(this)}
            logout={this.props.logout}
            getLoginModal={() => this.loginModal}
          />
          {!!this.state.loginModalVisible && <Login getInstance={(dom) => this.loginModal = dom} handleSubmit={this.handleSubmit.bind(this)} />}
        </div>
      );
    }
  }

  return connect((state) => ({
    userData: state.user,
  }), { login, logout })(Auth);
}